package org.ice4apps.api;

import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.ice4apps.service.IceServiceLocator;
import org.ice4apps.service.bean.EnterpriseAddServiceRequest;
import org.ice4apps.service.bean.EnterpriseGetServiceResponse;
import org.ice4apps.service.bean.EnterpriseListGetServiceResponse;
import org.ice4apps.service.bean.EntperpriseListEntry;
import org.ice4apps.service.bean.OfficeAddServiceRequest;
import org.ice4apps.service.bean.OfficeGetServiceResponse;
import org.ice4apps.service.bean.OfficeListEntry;
import org.ice4apps.service.bean.OfficeListGetServiceResponse;
import org.ice4apps.service.bean.OrganizationAddServiceRequest;
import org.ice4apps.service.bean.OrganizationGetServiceResponse;
import org.ice4apps.service.bean.OrganizationListEntry;
import org.ice4apps.service.bean.OrganizationListGetServiceResponse;
import org.ice4apps.service.bean.UserAddServiceRequest;
import org.ice4apps.service.bean.UserGetServiceResponse;
import org.ice4apps.service.bean.UserListEntry;
import org.ice4apps.service.bean.UserListGetServiceResponse;
import org.ice4apps.api.beans.EnterpriseAddRequest;
import org.ice4apps.api.beans.EnterpriseGetResponse;
import org.ice4apps.api.beans.EnterpriseListGetEntry;
import org.ice4apps.api.beans.EnterpriseListGetResponse;
import org.ice4apps.api.beans.OfficeAddRequest;
import org.ice4apps.api.beans.OfficeGetResponse;
import org.ice4apps.api.beans.OfficeListGetEntry;
import org.ice4apps.api.beans.OfficeListGetResponse;
import org.ice4apps.api.beans.OrganizationAddRequest;
import org.ice4apps.api.beans.OrganizationGetResponse;
import org.ice4apps.api.beans.OrganizationListGetEntry;
import org.ice4apps.api.beans.OrganizationListGetResponse;
import org.ice4apps.api.beans.UserAddRequest;
import org.ice4apps.api.beans.UserGetResponse;
import org.ice4apps.api.beans.UserListGetEntry;
import org.ice4apps.api.beans.UserListGetResponse;
import org.ice4apps.api.util.IceAPIServiceUtil;
import org.ice4apps.util.IceLog;
import com.sun.jersey.spi.resource.Singleton;

@Produces( { "application/xml", "application/json" })
@Consumes( { "application/xml", "application/json" })
@Path("/services")
@Singleton
public class IceAPIService {
    @GET
    @Produces("text/plain")
    @Consumes("text/plain")
    @Path("/system/validate")
    public Response validateSystem (@HeaderParam("Authorization") String auth) {
        IceLog.info (IceAPIService.class, "inside validate: "+auth);
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok ().build ();
    }

    @POST
    @Path("/enterprise")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response addEnterprise (@HeaderParam("Authorization") String auth, EnterpriseAddRequest req) {
        IceLog.info (IceAPIService.class, "inside addEnterprise: "+req.getName ()+" auth: "+auth);
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            EnterpriseAddServiceRequest sreq = new EnterpriseAddServiceRequest ();
            sreq.setName (req.getName ());
            IceServiceLocator.getIceSystemService ().addEnterprise (session, sreq);
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (req).build ();
    }

    @GET
    @Path("/enterprise/{name}")
    @Produces( { "application/xml", "application/json" })
    @Consumes({ "application/xml", "application/json" })
    public Response getEnterprise (@HeaderParam("Authorization") String auth, @PathParam("name") String name) {
        IceLog.info (IceAPIService.class, "inside getEnterprise: "+name+" auth: "+auth);
        EnterpriseGetResponse resp = new EnterpriseGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();           
            EnterpriseGetServiceResponse ent = IceServiceLocator.getIceSystemService ().getEnterprise (session, name);
            resp.setName (ent.getName ());
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
    
    @GET
    @Path("/enterprises")
    @Produces( { "application/xml", "application/json" })
    @Consumes({ "application/xml", "application/json" })
    public Response getEnterpriseList (@HeaderParam("Authorization") String auth) {
        IceLog.info (IceAPIService.class, "inside getEnterpriseList auth: "+auth);
        EnterpriseListGetResponse resp = new EnterpriseListGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();           
            EnterpriseListGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getEnterpriseList (session);
            List <EntperpriseListEntry> list = sResp.getList ();
            for (EntperpriseListEntry entry : list) {
                EnterpriseListGetEntry ent = new EnterpriseListGetEntry ();
                ent.setName (entry.getName ());
                IceLog.info (IceAPIService.class, "name: "+ent.getName ());
                resp.add (ent);
            }
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
    
    @POST
    @Path("/organization")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response addOrganization (@HeaderParam("Authorization") String auth, OrganizationAddRequest req) {
        IceLog.info (IceAPIService.class, "inside addOrganzation: "+req.getEnterpriseName ()+" auth: "+auth);
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            OrganizationAddServiceRequest sreq = new OrganizationAddServiceRequest ();
            sreq.setName (req.getName ());
            sreq.setEnterpriseName (req.getEnterpriseName ());
            sreq.setExtensionLength (req.getExtensionLength ());
            IceServiceLocator.getIceSystemService ().addOrganization (session, sreq);
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (req).build ();
    }
    
    @GET
    @Path("/organization/{name}")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response getOrganization (@HeaderParam("Authorization") String auth, @PathParam("name") String name) {
        IceLog.info (IceAPIService.class, "inside addOrganzation: "+name+" auth: "+auth);
        OrganizationGetResponse resp = new OrganizationGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            OrganizationGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getOrganization (session, name);
            resp.setEnterpriseName (sResp.getEnterpriseName ());
            resp.setExtensionLength (sResp.getExtensionLength ());
            resp.setName (sResp.getName ());
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
    
    @GET
    @Path("/enterprise/{enterpriseName}/organizations")
    @Produces( { "application/xml", "application/json" })
    @Consumes({ "application/xml", "application/json" })
    public Response getOrganizationList (@HeaderParam("Authorization") String auth, @PathParam("enterpriseName") String enterpriseName) {
        IceLog.info (IceAPIService.class, "inside getOrganizationList: "+enterpriseName +"auth: "+auth);
        OrganizationListGetResponse resp = new OrganizationListGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();           
            OrganizationListGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getOrganizationList (session, enterpriseName);
            List <OrganizationListEntry> list = sResp.getList ();
            for (OrganizationListEntry entry : list) {
                OrganizationListGetEntry org = new OrganizationListGetEntry ();
                org.setName (entry.getName ());
                org.setEnterpriseName (entry.getEnterpriseName ());
                resp.add (org);
            }
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
    
    @POST
    @Path("/office")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response addOffice (@HeaderParam("Authorization") String auth, OfficeAddRequest req) {
        IceLog.info (IceAPIService.class, "inside addOffice: "+req.getName ()+" auth: "+auth);
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            OfficeAddServiceRequest sreq = new OfficeAddServiceRequest ();
            sreq.setName (req.getName ());
            sreq.setOrganizationName (req.getOrganizationName ());
            sreq.setPrefix (req.getPrefix ());
            IceServiceLocator.getIceSystemService ().addOffice (session, sreq);
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (req).build ();
    }
    
    @GET
    @Path("/office/{name}")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response getOffice (@HeaderParam("Authorization") String auth, @PathParam("name") String name) {
        IceLog.info (IceAPIService.class, "inside getOffice: "+name+" auth: "+auth);
        OfficeGetResponse resp = new OfficeGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            OfficeGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getOffice (session, name);
            resp.setEnterpriseName (sResp.getEnterpriseName ());
            resp.setOrganizationName (sResp.getOrganizationName ());
            resp.setPrefix (sResp.getPrefix ());
            resp.setName (sResp.getName ());
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
    
    @GET
    @Path("/organization/{orgName}/offices")
    @Produces( { "application/xml", "application/json" })
    @Consumes({ "application/xml", "application/json" })
    public Response getOfficeList (@HeaderParam("Authorization") String auth, @PathParam("orgName") String orgName) {
        IceLog.info (IceAPIService.class, "inside getOfficeList: "+orgName +"auth: "+auth);
        OfficeListGetResponse resp = new OfficeListGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();           
            OfficeListGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getOfficeList (session, orgName);
            List <OfficeListEntry> list = sResp.getList ();
            for (OfficeListEntry entry : list) {
                OfficeListGetEntry office = new OfficeListGetEntry ();
                office.setName (entry.getName ());
                office.setEnterpriseName (entry.getEnterpriseName ());
                office.setOrganizationName (entry.getOrganizationName ());
                resp.add (office);
            }
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
   
    
    @POST
    @Path("/user")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response addUser (@HeaderParam("Authorization") String auth,UserAddRequest req) {
        IceLog.info (IceAPIService.class, "inside addUser: "+req.getUserName ()+" auth: "+auth);
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            UserAddServiceRequest sreq = new UserAddServiceRequest ();
            sreq.setOfficeName (req.getOfficeName ());
            sreq.setUserName (req.getUserName ());
            sreq.setPassword (req.getPassword ());
            sreq.setDomain (req.getDomain ());
            IceServiceLocator.getIceSystemService ().addUser (session, sreq);
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (req).build ();
    }
    
    @GET
    @Path("/user/{username}")
    @Produces( { "application/xml", "application/json" })
    @Consumes( { "application/xml", "application/json" })
    public Response getUser (@HeaderParam("Authorization") String auth, @PathParam("username") String userName) {
        IceLog.info (IceAPIService.class, "inside getUser: "+userName+" auth: "+auth);
        UserGetResponse resp = new UserGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();
            UserGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getUser (session, userName);
            resp.setOfficeName (sResp.getOfficeName ());
            resp.setUserName (sResp.getUserName ());
            resp.setDomain (sResp.getDomain ());
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
    
    
    
    @GET
    @Path("/office/{officeName}/users")
    @Produces( { "application/xml", "application/json" })
    @Consumes({ "application/xml", "application/json" })
    public Response getUserList (@HeaderParam("Authorization") String auth, @PathParam("officeName") String officeName) {
        IceLog.info (IceAPIService.class, "inside getUserList: "+officeName +"auth: "+auth);
        UserListGetResponse resp = new UserListGetResponse ();
        try {
            String session = IceServiceLocator
            .getIceSystemService ().login (IceAPIServiceUtil
                                           .getLoginRequest (auth));
            if (session == null)
                return Response.status (Status.UNAUTHORIZED).build ();           
            UserListGetServiceResponse sResp = IceServiceLocator.getIceSystemService ().getUserList (session, officeName);
            List <UserListEntry> list = sResp.getList ();
            for (UserListEntry entry : list) {
                UserListGetEntry user = new UserListGetEntry ();
                user.setUserName (entry.getUserName ());
                resp.add (user);
            }
            IceServiceLocator.getIceSystemService ().logout (session);
        } catch (Exception ex) {
            IceLog.error (IceAPIService.class, ex, "Error");
            return Response.serverError ().build (); 
        }
        return Response.ok (resp).build ();
    }
}